<template>
  <div class="third-manage-main">
    <c-form
      :model="ruleForm"
      :rules="rules"
      autocomplete="off"
      ref="ruleForm"
      label-width="85px"
      class="demo-ruleForm"
    >
      <div class="third-main-item">
        <div class="form-title">基本信息</div>
        <c-row class="third-main-row">
          <c-col :span="12">
            <c-form-item label="应用名称" prop="appName">
              <div class="max-size">
                <c-input
                  v-model.trim="ruleForm.appName"
                  placeholder="请输入应用名称，不超过100个字符"
                  maxlength="100"
                  @input="handelInputLength($event, 'appName', 100)"
                  :disabled="!show"
                ></c-input>
                <!-- <span>{{ ruleForm.appName.length }}/100</span> -->
              </div>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="应用类型" prop="appType">
              <c-radio-group v-model="ruleForm.appType" :disabled="!show">
                <c-radio :label="0">web应用</c-radio>
                <c-radio :label="1">App</c-radio>
              </c-radio-group>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="资源ID" prop="resource">
              <c-input v-model.trim="ruleForm.resource" placeholder="请输入资源ID" :disabled="!show"></c-input>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="授权模式" prop="authorizedGrantTypes">
              <c-select
                v-model="ruleForm.authorizedGrantTypes"
                placeholder="请选择授权模式"
                multiple
                :disabled="!show"
              >
                <c-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                ></c-option>
              </c-select>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="回调地址" prop="webServerRedirectUri">
              <c-input
                v-model.trim="ruleForm.webServerRedirectUri"
                placeholder="请输入合法的URL地址"
                :disabled="!show"
              ></c-input>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="应用描述" prop="appDescribe">
              <div class="max-size">
                <c-input
                  type="textarea"
                  v-model.trim="ruleForm.appDescribe"
                  :rows="3"
                  maxlength="300"
                  placeholder="请对应用进行描述，不超过300个字符"
                  @input="handelInputLength($event, 'appDescribe', 300)"
                  :disabled="!show"
                ></c-input>
                <!-- <span style="bottom:2px"
                  >{{ ruleForm.appDescribe.length }}/300</span
                >-->
              </div>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="应用LOGO">
              <div class="avatar-img">
                <img :src="ruleForm.appLogo" alt v-if="ruleForm.appLogo" />
                <img src="../../../../assets/default-upload.png" alt v-else />
              </div>
              <c-upload
                class="avatar-uploader"
                :show-file-list="false"
                action="/v1/yq/sysApp/uploadFile"
                :headers="{ access_token: token }"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <c-button size="small" plain type="primary" v-if="show">
                  <i class="el-icon-upload el-icon--left"></i>
                  上传自定义图标
                </c-button>
                <div slot="tip" class="el-upload__tip" v-if="show">支持扩展名：.jpg/.png/.gif 文件大小：200k以下</div>
              </c-upload>
            </c-form-item>
          </c-col>
        </c-row>
      </div>
      <div class="third-main-item">
        <div class="form-title">凭证信息</div>
        <c-row class="third-main-row">
          <c-col :span="12">
            <c-form-item label="Client ID">
              <span>{{ ruleForm.clientId }}</span>
              <i class="el-icon-document ml5" @click="handleCopySuccess(ruleForm.clientId)"></i>
            </c-form-item>
          </c-col>
          <c-col :span="12">
            <c-form-item label="Client Secret" prop="clientSecret" label-width="140px">
              <c-input
                v-model.trim="ruleForm.secret"
                type="password"
                disabled
                autocomplete="new-password"
              ></c-input>
              <span class="ml5">
                <i class="el-icon-document ml5" @click="handleCopySuccess(ruleForm.secret)"></i>
                <i
                  class="el-icon-refresh ml5"
                  @click="getVoucherInfo"
                  v-if="$route.params.type === '1'"
                ></i>
              </span>
            </c-form-item>
          </c-col>
        </c-row>
      </div>
      <!-- <div class='third-main-item'>
        <div class='form-title'>接口调用权限</div>
        <c-row class='third-main-row'>
          <c-col :span='12'>
            <c-form-item label="机构接口调用权限" prop="name" label-width='140px'>
              <c-switch
                class="switch"
                v-model="value5"
                active-text="开"
                inactive-text="关"
               >
              </c-switch>
            </c-form-item>
          </c-col>
          <c-col :span='12'>
            <c-form-item label="人员接口调用权限" prop="name" label-width='140px'>
              <c-switch
                class="switch"
                v-model="value5"
                active-text="开"
                inactive-text="关"
                >
              </c-switch>
            </c-form-item>
          </c-col>
        </c-row>
      </div>-->
      <c-form-item class="text-center" v-if="show">
        <c-button
          type="primary"
          @click="submitForm('ruleForm')"
          icon="el-icon-circle-check-outline"
        >确定</c-button>
        <c-button @click="cancelForm" icon="el-icon-circle-close-outline">取消</c-button>
      </c-form-item>
      <c-form-item class="text-center" v-if="!show">
        <c-button icon="el-icon-circle-close-outline" @click="cancelForm">返回</c-button>
      </c-form-item>
    </c-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import { getToken } from '@/utils/auth'
export default {
  name: 'newAddApplicat',
  data() {
    return {
      ruleForm: {
        appDescribe: '',
        appLogo: '',
        appName: '',
        appType: '',
        clientId: '',
        clientSecret: '',
        secret: '',
        appId: '',
        webServerRedirectUri: '',
        resource: '',
        authorizedGrantTypes: []
      },
      imageUrl: '',
      show: true,
      token: '',
      options: [
        { value: 'authorization_code', label: 'authorization_code' },
        { value: 'refresh_token', label: 'refresh_token' },
        { value: 'password', label: 'password' },
        { value: 'client_credentials', label: 'client_credentials' }
      ],
      rules: {
        appName: [
          { required: true, message: '请输入应用名称', trigger: 'blur' }
        ],
        appType: [
          {
            required: true,
            message: '请至少选择一个应用类型',
            trigger: 'change'
          }
        ],
        webServerRedirectUri: [
          { required: true, message: '请输入URL地址', trigger: 'blur' },
          {
            pattern: /((([A-Za-z]{3,9}:(?:\/\/)?)(?:[\-;:&=\+\$,\w]+@)?[A-Za-z0-9\.\-]+|(?:www\.|[\-;:&=\+\$,\w]+@)[A-Za-z0-9\.\-]+)((?:\/[\+~%\/\.\w\-_]*)?\??(?:[\-\+=&;%@\.\w_]*)#?(?:[\.\!\/\\\w]*))?)/,
            message: '请输入合法的URL地址',
            trigger: 'blur'
          }
        ],
        resource: [
          { required: true, message: '请输入资源ID', trigger: 'blur' }
        ],
        authorizedGrantTypes: [
          {
            required: true,
            message: '请至少选择一个授权模式',
            trigger: 'change'
          }
        ]
      }
    }
  },
  activated() {
    this.token = getToken()
    this.$refs['ruleForm'].clearValidate()
    this.show = this.$route.params.type !== '3'
    if (this.$route.params.type !== '1') {
      this.getInfoDetail()
    } else {
      this.ruleForm = {
        appDescribe: '',
        appLogo: '',
        appName: '',
        appType: '',
        secret: '',
        clientId: '',
        clientSecret: '',
        appId: '',
        webServerRedirectUri: '',
        resource: '',
        authorizedGrantTypes: []
      }
      this.getVoucherInfo()
    }
  },
  mounted() {
    this.$refs['ruleForm'] && this.$refs['ruleForm'].clearValidate()
  },
  methods: {
    // 获取详情信息
    getInfoDetail() {
      const url = '/v1/yq/sysApp/getSysAppDetail'
      request({
        url,
        method: 'get',
        params: { clientId: this.$route.params.clientId }
      }).then(({ data }) => {
        this.ruleForm = Object.assign({}, data)
      })
    },
    // 获取凭证信息
    getVoucherInfo() {
      const url = '/v1/yq/sysApp/createClientId'
      request({
        url,
        method: 'get'
      }).then(({ data }) => {
        this.ruleForm.clientId = data.clientId
        this.ruleForm.clientSecret = data.clientSecret
        this.ruleForm.secret = data.secret
      })
    },
    // 复制文本js
    handleCopySuccess(link) {
      const textArea = document.createElement('input')
      textArea.value = link
      const parentNode = document.body
      parentNode.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.style.display = 'none'
      this.$message.success('复制成功')
    },
    // 上传成功
    handleAvatarSuccess({ data }) {
      this.ruleForm.appLogo = data.url
    },
    // 上传格式大小验证
    beforeAvatarUpload(file) {
      const type = file.type.toLowerCase()
      const isJPG =
        type === 'image/jpeg' || type === 'image/png' || type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 0.2
      if (!isJPG) {
        this.$message.error('上传头像图片仅支持jpg、png、jif 格式!')
        return false
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 200KB!')
        return false
      }
    },
    // 处理字符串长度
    handelInputLength(val, type, len) {
      this.ruleForm[type] = this.ruleForm[type].slice(0, len)
    },
    // 提交表单
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.submitFormApi()
        } else {
          return false
        }
      })
    },
    // 提交表单API
    submitFormApi() {
      const url = '/v1/yq/sysApp/saveOrUpdate'
      const params = JSON.parse(JSON.stringify(this.ruleForm))
      params.authorizedGrantTypes = params.authorizedGrantTypes.join(',')
      request({
        url,
        method: 'post',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        data: params
      }).then(() => {
        const tip = this.$route.params.type === '1' ? '创建' : '编辑'
        this.$message.success(`${tip}成功`)
        setTimeout(() => {
          this.cancelForm()
        }, 1000)
      })
    },
    // 取消
    cancelForm() {
      this.$router.push({ path: `/siteconfig/thirdManage` })
    }
  }
}
</script>

<style lang="scss">
.third-manage-main {
  padding: 10px 40px 20px 20px;
  display: flex;
  flex-wrap: wrap;
  overflow: hidden;
  .el-input,
  .el-textarea {
    width: 400px;
  }
  .max-size {
    width: 400px;
    position: relative;
    span {
      position: absolute;
      right: 8px;
      bottom: 8px;
      background: #fff;
      color: #909399;
      line-height: 20px;
    }
  }
  .el-upload__tip {
    line-height: 1.6 !important;
  }
  .ml5 {
    margin-left: 5px;
    font-size: 16px;
    color: #409eff;
    cursor: pointer;
  }
  .avatar-img {
    float: left;
    width: 92px;
    height: 92px;
    border: 1px solid rgba(222, 222, 222, 1);
    opacity: 1;
    border-radius: 4px;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .avatar-uploader {
    float: left;
    margin-left: 20px;
  }
  .text-center {
    text-align: center;
  }
  .el-button [class*='el-icon-'] + span {
    margin-left: 0 !important;
  }
  i {
    margin-right: 0 !important;
  }
}
.form-title {
  color: #333;
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: bold;
  padding-bottom: 10px;
  border-bottom: 1px solid #dedede;
  text-indent: 16px;
}
.third-main-row {
  padding: 24px 0 40px;
}
.switch {
  width: 45px;
  .el-switch__label {
    position: absolute;
    display: none;
    color: #fff;
  }
  .el-switch__label--left {
    z-index: 1;
    right: -3px;
  }
  .el-switch__label--right {
    z-index: 1;
    right: 24px;
  }
  .el-switch__label.is-active {
    display: block;
  }
  .el-switch__core {
    width: 45px !important;
  }
}
</style>
